const fs = require("fs/promises");
const path = require("path");
const { isFile } = require("./isFile");
/**
 * 文件重命名
 * @param {*} dir
 * @param {*} getRename
 * @param {*} deep
 * @returns
 */
exports.renameFile = async function (dir, getRename, deep = false) {
  if (typeof getRename !== "function") {
    console.log("重命名方法有误");
    return;
  }
  const files = await fs.readdir(dir).catch((err) => {
    console.log("读取目录下文件夹失败", err.message);
    return [];
  });

  for (const file of files) {
    const oldPath = path.join(dir, file);

    // 判断是否为文件
    const isFileFlag = await isFile(oldPath);
    if (isFileFlag) {
      const newname = getRename(file);
      const newPath = path.join(dir, newname);
      if (newname !== file) {
        await fs
          .rename(oldPath, newPath)
          .then(() => {
            console.log("重命名成功", file, "===>", newname);
          })
          .catch((err) => {
            console.log("重命名失败", err.message);
          });
      }
    } else if (deep) {
      // 是否深度执行
      await exports.renameFile(oldPath, getRename, true);
    }
  }
};
